package org.example.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.Mapper.LogMapper;
import org.example.Pojo.LoginInfo;
import org.example.Pojo.OperateLog;
import org.example.Utils.LocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class OperationLogAspect {


    @Autowired
    private LogMapper logMapper;


    @Around("@annotation(org.example.anno.LogOperation)")
    public Object operationLog(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("Operation log start");
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        log.info("Operation log end time: {} ms", endTime - startTime);

        long elapsedTime = endTime - startTime;

        OperateLog operateLog = new OperateLog();


        operateLog.setCostTime(elapsedTime);
        operateLog.setOperateEmpId(currentId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setReturnValue(result.toString());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));

        logMapper.insert(operateLog);

        return result;


    }

    private Integer currentId() {
        return LocalUtils.getCurrentId();
    }
}
